package org.bookie.web.pages;

import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.dojo.html.Dialog;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.bookie.framework.CommonBasePage;
import org.bookie.model.Group;
import org.bookie.model.Role;
import org.bookie.model.security.Access;
import org.bookie.model.services.GroupDAO;

/**
 * This page is used by {@link User}s to create new {@link Group}s. 
 * 
 * @author Igor Drobiazko
 *
 */
@Access(role = Role.USER)
public abstract class AddGroup extends CommonBasePage  implements PageBeginRenderListener{
	
	/**Client identifier of the div containing group form and error messages*/
	public static final String CONTAINER = "container";
	/**Client identifier of confirmation dialog*/
	public static final String DIALOG = "confirmGroupDialog";
	
	/**
	 * {@inheritDoc}
	 */
	public void pageBeginRender(PageEvent event) {
		if(getGroup()==null){
			setGroup(new Group());
		}
	}
	
	/**
	 * Validates the form and shows the confirmation dialog.
	 */
	public void confirm(){
		if (getDelegate().getHasErrors()) {
			updateComponents(CONTAINER);
			return;
		}
		Group found = getGroupDAO().findByName(getGroup().getName());
		if(found!=null){
			recordError("addgroup.form.error.groupExists");
			updateComponents(CONTAINER);
			return;
		}
		Dialog dialog = (Dialog)getComponent(AddGroup.DIALOG);
		dialog.show();
		updateComponents(AddGroup.DIALOG);
	}
	
	/**
	 * Makes the created {@link Group} persistent and hides the confirmation dialog.
	 */
	public void save(){
		getGroupDAO().makePersistent(getGroup());
		cancel();
		setMessage(getMessages().getMessage("addgroup.confirm.message"));
		updateComponents(CONTAINER);
	}
	
	/**
	 * Hides the confirmation dialog.
	 * This method is called when the user cancels or finalizes the group creation.
	 */
	public void cancel(){
		setGroup(null);
		Dialog dialog = (Dialog)getComponent(AddGroup.DIALOG);
		dialog.hide();
		getResponseBuilder().updateComponent(AddGroup.DIALOG);
	}
	
	/**
	 * Injected group service
	 * @return instance of GroupDAO
	 */
	@InjectObject("service:bookie.model.GroupDAO")
	public abstract GroupDAO getGroupDAO();
	
	/**
	 * Get the {@link Group}
	 * @return instance of Group
	 */
	@Persist("session")
	public abstract Group getGroup();
	
	/**
	 * Set the {@link Group}
	 * @param group group to set
	 */
	public abstract void setGroup(Group group); 
}
